import { Md5 } from 'ts-md5/dist/md5';
import Taro from '@tarojs/taro';

const generateRandomString = (length) => {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
};

export const commonHeader = (url: string) => {
  const systemId = 'QD-HAIER-MINIPROGRAM';
  const systemKey = '8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b';
  const sequenceId = generateRandomString(32);
  const timestamp = new Date().getTime().toString();

  const header = {
    'Content-Type': 'application/json;charset=utf8',
    systemId,
    sequenceId,
    sign: Md5.hashStr(`${url}${systemId}${systemKey}${timestamp}${sequenceId}`), // 签名
    timestamp,
  };
  return header;
};

export const getClientId = () => {
  const clientId: any =
    Taro.getSystemInfoSync().system.replace(/\s+/g, '').replace(/[.]/g, '') +
    new Date().valueOf();
  return clientId;
};

//登录header
export const loginHeader = () => {
  const header = {
    'Content-Type': 'application/x-www-form-urlencoded',
  };
  return header;
};
//头像上传header
export const avatarUploadHeader = () => {
  const token: any = Taro.getStorageSync('access_token_login');
  const header = {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${token}`,
  };
  return header;
};
// 获取应用级token
export const tokenHeader = () => {
  const token: any = Taro.getStorageSync('access_token');
  const header = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  };
  return header;
};

//登录后获取的token
export const loginedTokenHeader = () => {
  const token: any = Taro.getStorageSync('access_token_login');
  const header = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  };
  return header;
};
